#!/usr/bin/python
'''
*************************************************************************************************************************************************
Hypergraph input file generator
Version: 1.0
Author: Victor Codocedo
Description: This script generates an rcf file of context for coron
*************************************************************************************************************************************************
'''
import psycopg2
import sys
from context_functions import *

if len(sys.argv)<2: 
	exit()
db = sys.argv[1]

myconnection = "dbname='%s' user='kyori' host='bunkers' password='contexta'"%db

conn = psycopg2.connect(myconnection)
cur = conn.cursor()

sql = "select concept.id, publication.id from concept, pub_concept, publication where concept.id = id_concept and publication.id = id_publication order by identifier"
#sql = "select auth_name,concept.label from concept, pub_concept, publication, pub_auth, author where concept.id = id_concept and publication.id = pub_concept.id_publication and pub_auth.id_publication = publication.id and author.id=id_author order by label"
table = []

cur.execute(sql)
table.append(cur.fetchall())

docs = []
terms = []
termdoc = {}
for rows in table:
	for r in rows:
		doc = int(r[1])
		term = int(r[0])
		if doc not in docs:
			docs.append(doc)
		if term not in terms:
			terms.append(term)
		if term not in termdoc:
			termdoc[term] = []
		termdoc[term].append(doc)

terms.sort()
docs.sort()

matrix = []
for t in terms:
	row = []
	for d in docs:
		if d in termdoc[t]:
			row.append(1)
		else:
			row.append(0)
	matrix.append(row)

fp = writeContext(db+".rcf",matrix,terms,docs,context_name=db+" Context", dataset_name="term_document")

cur.close()
conn.close()
